<template>
	<view :data-theme="theme">
		<view class="tab-button">
			<button v-if="data.type == 1 || data.type == 2">{{data.name ? data.name : ''}}</button>
			<view v-if="data.type == 3" class="city_name" style="display: inline-block;"
				v-for="(ele,indexn) in data.depotCityList">
				<span
					style="margin: 10rpx; display: inline-block; font-weight: bold;background-color: #FFF;padding: 20rpx;border-radius: 18rpx;">{{ele.name ? ele.name : ''}}</span>
			</view>
		</view>
		<!-- 修改营业信息 -->
		<view v-if="data.type == 1 || data.type == 3">
			<view class="item_top" style="margin: 10px 25rpx;">
				<text class="header">营业信息</text>
			</view>
			<view class="card">
				<view class="card-menu" style="padding: 20px 10px;">
					<view style="float: left;font-weight: bold;">
						营业状态
					</view>
					<!-- 营业状态 -->
					<view style="margin: 10px 0 10px 0">
						<view class="sku-select1">
							<view class="uni-flex uni-row" style="-webkit-flex-wrap: wrap;flex-wrap: wrap;">
								<view class="flex-text" :class='item.sku == attrValue.sku?"right-class-active":""'
									v-for="(item,index) in skuArr" :key="index" @click='tapAttr(item)'>{{item.sku}}
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view v-if="attrValue.id == 1 ">
				<view class="card2">
					<view class="title" style="display: block;">
						营业日
					</view>
					<view class="middle-button">
						<!-- <u-checkbox-group v-model="checkboxValue1" @change="checkboxChange" iconPlacement="left"
							placement="column">
							<u-checkbox activeColor="#3c9cff" label="蓝色" :customStyle="{marginBottom: '10px'}"
								v-for="(item, index) in checkboxList1" :key="index" :label="item.name"
								:name="index + 1">
							</u-checkbox>
						</u-checkbox-group> -->

						<checkbox-group class="checke_list" v-model="checkboxValue1" @change="checkboxChange">
							<view class="uni-list-cell uni-list-cell-pd checke_item"
								v-for="(item, index) in checkboxList1" :key="index">
								<view class="item_top">
									<checkbox :value="item.id.toString()" :checked="isChecked(item.id)"
										class="round-checkbox" />
									<view class="item_img">
										{{item.name}}
									</view>
								</view>
							</view>
						</checkbox-group>
					</view>
				</view>
				<view class="card">
					<view class="title" style="display: block;">
						营业时段（24小时）
					</view>
					<view style="margin:20px;display: flex;">
						<picker mode="time" :value="Timevalue" @change="confirmDate" @cancel="cancel">
							<view @click="show = true" class="message_bottom" style="display: inline;">
								<span>开始时间：</span>
								<span v-if="Timevalue == ''">{{data.businessBeginHoursEveryDay}}</span>
								{{this.Timevalue}}
							</view>
						</picker>
						至
						<picker mode="time" :disabled="endTimeChose" :value="Timevalue2" @change="confirmDate2"
							@cancel="cancel2">
							<view @click="haveTime" class="message_bottom" style="display: inline;">
								<span>结束时间：</span>
								<span v-if="Timevalue2 == ''">{{data.businessEndHoursEveryDay}}</span>
								{{this.Timevalue2}}
							</view>
						</picker>
						<!-- <u-datetime-picker :show="show" v-model="Timevalue" mode="time" @confirm="confirmDate"
							@close="show = false" @cancel="cancel"></u-datetime-picker> -->

						<!-- <u-datetime-picker :show="show2" v-model="Timevalue2" mode="time" @confirm="confirmDate2"
							@close="show2 = false" @cancel="cancel2"></u-datetime-picker> -->
					</view>
				</view>
			</view>
		</view>
		<!-- 修改歇业信息 -->
		<view v-if="data.type == 2 ||data.type == 3">
			<view class="item_top" style="margin: 10px 25rpx;">
				<text class="header">歇业信息</text>
			</view>
			<view class="card">
				<view class="card-menu" style="padding: 20px 10px;">
					<view style="float: left;font-weight: bold;">
						是否设置自动歇业
					</view>

					<!-- 歇业状态 -->
					<view style="margin: 10px 0 10px 0">
						<view class="sku-select1">
							<view class="uni-flex uni-row" style="-webkit-flex-wrap: wrap;flex-wrap: wrap;">
								<view class="flex-text" :class='item.sku == attrValue2.sku?"right-class-active":""'
									v-for="(item,index) in skuArr2" :key="index" @click='tapAttr2(item)'>{{item.sku}}
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="card" v-show="attrValue2.id == 1">
				<view class="card-menu">
					<view class="title" style="display: block;">
						设置自动歇业日期
					</view>
					<!-- <view style="margin: 10px 0 10px 0">
						最多可添加五段
					</view> -->
				</view>
				<view style="background-color: #FFF;">
					<view v-for="(item,index) in ListData" :key="index" class="violation_message_time">
						<view class="message_bottom" style="display: inline;">{{item.beginTime}}</view>
						<view class="violation_message">
							至
						</view>
						<view class="message_bottom" style="display: inline;">{{item.endTime}}</view>
						<view class="violation_message" style="display: inline;" @click="delateDate(index)">
							删除
						</view>
					</view>
					<!-- 日期组件 -->
					<!-- <u-calendar :defaultDate="calendar.defaultDate" :monthNum="calendar.monthNum" :color="bgColor"
						:show="calendarShow" :mode="'range'" :closeOnClickOverlay="true" @confirm="calendarConfirm"
						@close="calendarShow = false">
					</u-calendar> -->
					<view class="card">
						<uni-datetime-picker v-model="range" type="daterange" @change="calendarConfirm"
							:color="bgColor">
							<button @click="calendarShow = true">添加日期</button>
						</uni-datetime-picker>
					</view>

				</view>
			</view>
		</view>
		<view style="height: 160rpx;display: block;"></view>
		<view class="title-bottom"
			style="position: fixed;bottom: 0px;width: 100%;padding: 10px;background-color: #FFF;">
			<view class="bottom-button">
				<button style="margin:10px ;line-height: 64rpx;font-weight: bold;" class="plain_bgColor"
					@click="Goback">退出</button>
			</view>
			<view class="bottom-button">
				<button v-if="data.type == 1" class="bg_color"
					style="margin:10px ;line-height: 64rpx; font-weight: bold;color: #FFF;"
					@click="updataBusiness">完成配置</button>
				<button v-if="data.type == 2" class="bg_color"
					style="margin:10px ;line-height: 64rpx; font-weight: bold;color: #FFF;"
					@click="automatical">完成配置</button>
				<button v-if="data.type == 3" class="bg_color"
					style="margin:10px ;line-height: 64rpx; font-weight: bold;color: #FFF;"
					@click="batchSetting">完成配置</button>
			</view>
		</view>

	</view>
</template>

<script>
	import {
		businessModifyBusinessTimeApi,
		businessModifyAutomaticallyApi,
		businessModifyBusinessInformationApi,
		batSetBusinessStatusApi
	} from '@/api/businessStatus.js'
	import {
		setThemeColor
	} from '../../../utils/setTheme';
	let app = getApp();
	export default {
		data() {
			return {
				bgColor: "#ffffff",
				theme: app.globalData.theme,
				data: {},
				itemId: "",
				skuArr: [{
					sku: "正常营业",
					id: '1'
				}, {
					sku: "临时歇业",
					id: '2'
				}],
				skuArr2: [{
					sku: "是",
					id: '1'
				}, {
					sku: "否",
					id: '2'
				}],
				attrValue: [],
				attrValue2: [],
				checkboxValue1: [],
				// 基本案列数据
				checkboxList1: [{
						name: '周一',
						id: 1,
					},
					{
						name: '周二',
						id: 2,
					},
					{
						name: '周三',
						id: 3,
					},
					{
						name: '周四',
						id: 4,
					},
					{
						name: '周五',
						id: 5,
					},
					{
						name: '周六',
						id: 6,
					},
					{
						name: '周日',
						id: 7,
					},
				],

				value: "",
				calendarShow: false, //时间日期选择框
				calendar: {
					defaultDate: [],
				},
				newArr: {
					beginTime: "",
					endTime: "",
				},
				ListData: [],
				// ---
				//营业日期选择
				show: false,
				Timevalue: '',
				totalMinutes: '', //分钟
				show2: false,
				Timevalue2: '',
				totalMinutes2: '', // 分钟2
				// ------
				range: [],
				endTimeChose: true,
			};
		},
		onLoad(options) {
			this.bgColor = setThemeColor();
			uni.setNavigationBarColor({
				frontColor: '#ffffff',
				backgroundColor: this.bgColor,
			});
			this.data = JSON.parse(options.data);
			console.log(this.data, 'data')
			//使用传递过来的对象 data
			//回显歇业时间
			if (this.data.automaticallyDate) {
				const newArr = JSON.parse(this.data.automaticallyDate);
				this.ListData = newArr;
			}
			//是否歇业判断
			if (this.data.businessStatus == '0') {
				this.attrValue.sku = "临时歇业";
				this.attrValue.id = 2;
			} else {
				this.attrValue.sku = "正常营业";
				this.attrValue.id = 1;
			};
			this.attrValue2.sku = "是";
			this.attrValue2.id = 1;
			if (this.data.monday) {
				if (this.data.monday == 1) {
					this.checkboxValue1 = [1, 2, 3, 4, 5, 6, 7]
				} else {
					this.checkboxValue1 = JSON.parse(this.data.monday);
				}
			}

			//加载日期组件数据
			this.chooseTimed();
		},

		methods: {
			//营业状态 改变
			tapAttr(skuItem) {
				this.attrValue = skuItem;
			},
			//自动歇业 改变
			tapAttr2(skuItem) {
				this.attrValue2 = skuItem;
			},
			Goback() {
				uni.navigateBack()
			},
			//复选框
			checkboxChange(n) {
				// this.monday = n;
				let checkboxValue = n.detail.value.map((item) => JSON.parse(item))
				this.monday = checkboxValue;
			},
			isChecked(id) {
				return this.checkboxValue1 && this.checkboxValue1.includes(id);
			},
			//时间选择确认按钮
			confirmDate(date) {
				this.Timevalue = date.detail.value;
				const timeArr = date.detail.value.split(':');
				const hours = parseInt(timeArr[0]);
				const minutes = parseInt(timeArr[1]);
				this.totalMinutes = hours * 60 + minutes;
				console.log('totalMinutes', this.totalMinutes, date)
				this.show = false;
			},
			cancel() {
				this.show = false;
			},
			haveTime() {
				if (this.Timevalue) {
					this.show2 = true;
					this.endTimeChose = false;
				} else {
					uni.showModal({
						title: '提示',
						content: '请先选择开始时间',
						showCancel: false,
						confirmText: '知道了'
					})
					return
					this.show2 = false;
					this.endTimeChose = true;
				}
			},
			//结束时间选择确认按钮
			confirmDate2(date) {
				const timeArr = date.detail.value.split(':');
				const hours = parseInt(timeArr[0]);
				const minutes = parseInt(timeArr[1]);
				this.totalMinutes2 = hours * 60 + minutes;
				if (this.totalMinutes2 > this.totalMinutes) {
					this.Timevalue2 = date.detail.value;
					this.show2 = false;
				} else {
					uni.showToast({
						title: ' 结束时间与开始时间不符，请重新设置 ',
						icon: 'error',
						duration: 2000
					});
					this.show2 = true;
				}
			},
			cancel2() {
				if (this.totalMinutes2 > this.totalMinutes) {
					this.show2 = false;
				} else {
					this.Timevalue2 = '';
					this.show2 = false;
				}
			},
			//日期选择确认
			calendarConfirm(dates) {
				this.newArr = {
					beginTime: "",
					endTime: "",
				};
				this.calendar.defaultDate = dates;
				this.newArr.beginTime = dates[0];
				this.newArr.endTime = dates[dates.length - 1];
				if (this.ListData == null || this.ListData == 0) {
					this.ListData = [];
				}
				this.ListData.push(this.newArr);
				this.calendarShow = false;
			},
			// 设置默认日期，最小日期是今天，往后选
			chooseTimed() {
				let date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();
				let minyear = year - 1;
				this.calendar.defaultDate = year + '-' + month + '-' + day;
			},
			//临时歇业
			modifyBusiness() {

			},
			// 修改具体营业时间
			async updataBusiness() {
				if (this.attrValue.id == 1) {
					//判断开始时间
					if (this.totalMinutes) {
						this.totalMinutes = this.totalMinutes
					} else {
						if (this.data.businessBeginHoursEveryDay == undefined) {
							return uni.showToast({
								title: '请选择营业开始时段',
								icon: 'error',
								duration: 2000
							});
						}
						const [beginHours, beginMinutes] = this.data.businessBeginHoursEveryDay.split(":");
						const businessBeginHoursEveryDay = parseInt(beginHours) * 60 + parseInt(beginMinutes);
						this.totalMinutes = businessBeginHoursEveryDay;
					};
					//判断结束时间
					if (this.totalMinutes2) {
						this.totalMinutes2 = this.totalMinutes2
					} else {
						if (this.data.businessEndHoursEveryDay == undefined) {
							return uni.showToast({
								title: '请选择营业结束时段',
								icon: 'error',
								duration: 2000
							});
						}
						const [endHours, endMinutes] = this.data.businessEndHoursEveryDay.split(":");
						const businessEndHoursEveryDay = parseInt(endHours) * 60 + parseInt(endMinutes);
						this.totalMinutes2 = businessEndHoursEveryDay;
					}
					if (!this.monday) {
						return uni.showToast({
							title: '请选择营业日',
							icon: 'error',
							duration: 2000
						});
					}
					const businessTimeData = {
						id: this.data.id,
						businessBeginHoursEveryDay: this.totalMinutes.toString(),
						businessEndHoursEveryDay: this.totalMinutes2.toString(),
						businessStatus: '1',
						monday: JSON.stringify(this.monday),
					};
					await businessModifyBusinessTimeApi(businessTimeData);
				} else {
					const businessData = {
						id: this.data.id,
						statusId: '',
					};
					if (this.attrValue.id == 2) {
						businessData.statusId = '0';
					} else {
						businessData.statusId = '1';
					}
					await businessModifyBusinessInformationApi(businessData)
				}

				// this.goBack();
			},
			//删除所选日期
			delateDate(ele) {
				this.ListData.splice(ele, 1) //使用splice 方法删除当前对象
			},
			// 自动歇业设置
			async automatical() {
				const automaticalData = {};
				if (this.attrValue2.id == 1) {
					automaticalData.isAutomatically = '1';
					automaticalData.automaticallyDate = JSON.stringify(this.ListData);
					if (!automaticalData.automaticallyDate.length) {
						return uni.showToast({
							title: '请选择歇业日期范围',
							icon: 'error',
							duration: 2000
						});
					}
				} else {
					automaticalData.isAutomatically = '0';
					delete automaticalData.automaticallyDate;
				};

				automaticalData.id = this.data.id;
				const res = await businessModifyAutomaticallyApi(automaticalData);
				// this.goBack();
			},
			goBack() {
				//刷新并返回上一级
				uni.navigateBack({
					delta: 1,
					success: function(res) {
						// 获取上级页面栈实例
						const pages = getCurrentPages();
						const prevPage = pages[pages.length - 2]; // 上级页面实例
						// 调用上级页面的刷新数据方法
						prevPage.initData();
					}
				});
			},
			//批量设置营业城市信息
			batchSetting() {
				// 自动歇业
				const automaticalData = {};
				if (this.attrValue2.id == 1) {
					if (!this.ListData.length) {
						return uni.showToast({
							title: '请选择歇业日期范围',
							icon: 'error',
							duration: 2000
						});
					}
					automaticalData.isAutomatically = '1';
					automaticalData.automaticallyDate = JSON.stringify(this.ListData);
				} else {
					automaticalData.isAutomatically = '0';
					delete automaticalData.automaticallyDate;
				};
				let businessTimeData = {};
				//营业日期
				if (this.attrValue.id == 1) {
					if (!this.monday) {
						return uni.showToast({
							title: '请选择日期',
							icon: 'error',
							duration: 2000
						});
					}
					//判断开始时间
					if (this.totalMinutes) {
						this.totalMinutes = this.totalMinutes
					} else {
						if (this.data.businessBeginHoursEveryDay == undefined) {
							return uni.showToast({
								title: '请选择营业时段',
								icon: 'error',
								duration: 2000
							});
						}
						const [beginHours, beginMinutes] = this.data.businessBeginHoursEveryDay.split(":");
						const businessBeginHoursEveryDay = parseInt(beginHours) * 60 + parseInt(beginMinutes);
						this.totalMinutes = businessBeginHoursEveryDay;
					};
					//判断结束时间
					if (this.totalMinutes2) {
						this.totalMinutes2 = this.totalMinutes2
					} else {
						if (this.data.businessEndHoursEveryDay == undefined) {
							return uni.showToast({
								title: '请选择营业结束时段',
								icon: 'error',
								duration: 2000
							});
						}
						const [endHours, endMinutes] = this.data.businessEndHoursEveryDay.split(":");
						const businessEndHoursEveryDay = parseInt(endHours) * 60 + parseInt(endMinutes);
						this.totalMinutes2 = businessEndHoursEveryDay;
					}

					businessTimeData.businessBeginHoursEveryDay = this.totalMinutes.toString();
					businessTimeData.businessEndHoursEveryDay = this.totalMinutes2.toString();
					businessTimeData.businessStatus = '1';
					businessTimeData.monday = JSON.stringify(this.monday);
					// console.log('营业时间', businessTimeData)
				} else {
					businessTimeData.id = this.data.id
				};
				let businessCloseDTOS = {};
				if (this.attrValue.id == 2) {
					businessCloseDTOS.statusId = '0';
				}
				//  else {
				// 	businessTimeData.statusId = '1';
				// }
				let modifyBusinessStatusDTOS = [];
				for (let item of this.data.depotCityList) {
					modifyBusinessStatusDTOS.push({
						id: item.id
					})
				};
				const newModifyBusinessStatusDTOS = modifyBusinessStatusDTOS.map(item => {
					const newItem = {
						...item
					}; // 使用对象解构创建新的对象
					Object.entries(businessTimeData).forEach(([key, value]) => {
						newItem[key] = value; // 添加属性和属性值
					});
					return newItem;
				});

				// 是否自己动歇业
				let businessModifyAutomaticallyDTOS = [];
				for (let item of this.data.depotCityList) {
					businessModifyAutomaticallyDTOS.push({
						id: item.id
					})
				};
				const newBusinessModifyAutomaticallyDTOS = businessModifyAutomaticallyDTOS.map(item => {
					const newItem = {
						...item
					}; // 使用对象解构创建新的对象
					Object.entries(automaticalData).forEach(([key, value]) => {
						newItem[key] = value; // 添加属性和属性值
					});
					return newItem;
				});

				// 是否自己动歇业
				let businessModifyBusinessIsCloseDTOS = [];
				for (let item of this.data.depotCityList) {
					businessModifyBusinessIsCloseDTOS.push({
						id: item.id
					})
				};
				const newBusinessModifyBusinessIsCloseDTOS = businessModifyBusinessIsCloseDTOS.map(item => {
					const newItem = {
						...item
					}; // 使用对象解构创建新的对象
					Object.entries(businessCloseDTOS).forEach(([key, value]) => {
						newItem[key] = value; // 添加属性和属性值
					});
					return newItem;
				});

				let batSetValue = {
					businessModifyAutomaticallyDTOS: newBusinessModifyAutomaticallyDTOS,
					modifyBusinessStatusDTOS: newModifyBusinessStatusDTOS,
					businessModifyBusinessIsCloseDTOS: newBusinessModifyBusinessIsCloseDTOS,
				};

				if (this.attrValue.id == 2) {
					delete batSetValue.modifyBusinessStatusDTOS
				} else if (this.attrValue.id == 1) {
					delete batSetValue.businessModifyBusinessIsCloseDTOS
				}
				batSetBusinessStatusApi(batSetValue).then((res) => {
					if (res.code == 200) {
						return uni.showToast({
							title: '配置完成',
							icon: 'success',
							duration: 2000
						});
					}
				})
			}
		}
	}
</script>

<style lang="scss">
	.bg_color {
		@include main_bg_color(theme);
	}

	.plain_bgColor {
		@include main_color(theme);
		@include main_bg_rgba_color(theme, 0.05);
		border: 1rpx solid;
	}


	.header {
		font-size: 18px;
		font-weight: bold;
		-webkit-text-stroke-width: 700;
	}

	.card {
		margin: 20rpx 20rpx 20rpx 20rpx;
		background-color: #fff;
		border-radius: 20rpx;
		padding: 10px;
	}

	.card2 {
		margin: 20rpx 20rpx 20rpx 20rpx;
		background-color: #fff;
		border-radius: 20rpx;
		display: flex;
		flex-wrap: wrap;
		padding: 8px;
	}

	.tab-button {
		margin: 20px;
		border-radius: 10px;
	}

	.item_top {
		display: flex;
		justify-content: space-between;
		padding: 10px 0;
		font-weight: bold;
		font-size: 16px;
	}

	.card-menu {
		display: flex;
		justify-content: space-between;
		flex-wrap: wrap;
	}

	.title {
		margin: 10px;
		font-weight: bold;
	}

	.middle-button {
		margin: 10px;
		display: block;
	}

	.sku-select1 {
		.flex-text {
			margin: 8rpx 8rpx;
			background-color: #f7f7f7;
			line-height: 62rpx;
			text-align: center;
			color: #777;
			padding: 10rpx 20rpx;
			font-size: 24rpx;
			border-radius: 10rpx;
			border: 1rpx solid #FFF;
		}

		.right-class-active {
			@include main_color(theme);
			@include main_bg_rgba_color(theme, 0.05);
			border: 1rpx solid;
		}
	}

	.title-bottom {
		display: flex;
		justify-content: space-between;
	}

	.bottom-button {
		width: 45%;

	}

	.violation_message_time {
		display: block;
		text-align: center;
		margin-bottom: 10px;
	}

	.message_bottom {
		border-radius: 5px;
		padding: 10px;
		@include main_color(theme);
		@include main_bg_rgba_color(theme, 0.05);
	}

	.violation_message {
		margin: 10px;
		display: inline-block;
	}
</style>